#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <GL/glut.h>

void screenshot(){
int width   =  glutGet(GLUT_WINDOW_WIDTH);
	  int height  =  glutGet(GLUT_WINDOW_HEIGHT);
	  int i,j;
	  unsigned char *image= (unsigned char *)malloc(3*width*height*sizeof(char));
	  float time = glutGet(GLUT_ELAPSED_TIME) / 100.0;
	  char* fileName;
	  //printf("VALORE DI TIME = %s\n",time);
	  asprintf (&fileName, "screenshot/_screenshot_%f.jpg", time);
//	  strcat(fileName, time);
	  FILE *fp = fopen(fileName, "w");
	  glPixelStorei (GL_PACK_ALIGNMENT,1);
	  glReadBuffer (GL_BACK_LEFT);
	  glReadPixels(0,0,width,height,GL_RGB,GL_UNSIGNED_BYTE,image);
	  
	  fprintf(fp, "P6\n");
	  fprintf(fp, "%d %d\n", width, height);
	  fprintf(fp, "255\n");
	 
	  for (i=height-1; i>=0; i--) {
	  for (j=0; j<width; j++) {
		  fprintf(fp, "%c%c%c", 
			image[i*width*3 + j*3+0], 
			image[i*width*3 + j*3+1],
			image[i*width*3 + j*3+2]);
		}
	  }
	
	  free(image);
	  fclose(fp);
}


